/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import {
  AddAreaPost,
  CloseAreaPost,
  deleteArea,
  SendCode,
  applyCloseDak,
  noPwdLogin,
  getApplyList,
  subList,
} from '@/services/api';
import {
  zyGetSubPostStations,
  zyGetSubPostStationsToBeChecked,
  zyForbidOrRecover,
  zyAudit,
  zyChangeBranch,
  zyExport,
} from '@/services/zyAcount';
import { approved, charging, getPostInfo, modifyPostInfo, getZyAccountList } from '@/services/area';
import { isLegalData } from '@/utils/utils';
import { message } from 'antd';

export default {
  namespace: 'area',

  state: {
    subordinates: {
      list: [],
      paginations: null,
    },
    independent: {
      list: [],
      paginations: null,
    },
    audit: {
      list: [],
      paginations: null,
    },
    auditrefus: {
      list: [],
      paginations: null,
    },
    apply: {
      list: [],
      paginations: null,
    },
    forbidden: {
      list: [],
      paginations: null,
    },
    businessInfoMap: [],
    baseInfoMap: [
      {
        title: '驿站名称',
        key: 'inn_name',
      },
      {
        title: '注册账号',
        key: 'phone',
      },
      {
        title: '站点编号',
        key: 'cm_id',
      },
      {
        title: '联系人',
        key: 'concat_name',
      },
      {
        title: '联系电话',
        key: 'concat_phone',
      },
      {
        title: '驿站注册地址',
        key: 'address',
      },
      {
        title: '注册时间',
        key: 'create_at',
      },
      {
        title: '审核时间',
        key: 'join_at',
      },
    ],
    searchValue: {},
  },

  effects: {
    *subList({ payload, __dva_resolve }, { call, put }) {
      const {
        is_district,
        key,
        district,
        keyword,
        pageNum,
        code: codeArr,
        export: exportStatus = '',
        action,
        recharge,
        area_id,
      } = payload;
      const params = {
        is_district,
        keyword,
        page: pageNum,
        code: codeArr,
        export: exportStatus,
        recharge,
        area_id,
      };
      const response = yield call(subList, params);
      if (!response) return;
      if (action === 'export') {
        __dva_resolve(response);
        return;
      }
      const { code, data = {}, msg } = response || {};
      const { list, page, total, pageSize } = data;
      let array = list;
      if (code == 0 && list) {
        if (Object.keys(list).length > 0) {
          array = list;
        } else {
          array = [];
          if (!district) {
            message.error('暂无数据');
          }
        }
        if (is_district == 0) {
          yield put({
            type: 'save',
            payload: {
              subordinates: {
                list: array,
                key,
                keyword,
                area_id,
                paginations: {
                  page,
                  count: total,
                  pageSize,
                },
              },
            },
          });
        } else if (is_district == 1) {
          yield put({
            type: 'save',
            payload: {
              independent: {
                list: array,
                key,
                keyword,
                paginations: {
                  page,
                  count: total,
                  pageSize,
                },
              },
            },
          });
        } else if (is_district == 2) {
          yield put({
            type: 'save',
            payload: {
              audit: {
                list: array,
                key,
                keyword,
                paginations: {
                  page,
                  count: total,
                  pageSize,
                },
              },
            },
          });
        } else if (is_district == 3) {
          yield put({
            type: 'save',
            payload: {
              apply: {
                list: array,
                key,
                keyword,
                paginations: {
                  page,
                  count: total,
                  pageSize,
                },
              },
            },
          });
        }
      } else {
        if (is_district == 0) {
          yield put({
            type: 'save',
            payload: {
              subordinates: {
                list: [],
                key,
              },
            },
          });
        } else if (is_district == 1) {
          yield put({
            type: 'save',
            payload: {
              independent: {
                list: [],
                key,
              },
            },
          });
        } else if (is_district == 2) {
          yield put({
            type: 'save',
            payload: {
              audit: {
                list: [],
                key,
              },
            },
          });
        } else if (is_district == 3) {
          yield put({
            type: 'save',
            payload: {
              apply: {
                list: [],
                key,
              },
            },
          });
        }
        if (!district) {
          message.error(msg);
        }
      }
      __dva_resolve({
        list: isLegalData(array),
        paginations: {
          page,
          count: total,
          pageSize,
        },
      });
    },
    *getApplyList({ payload, __dva_resolve }, { call, put }) {
      const {
        is_district,
        key,
        district,
        keyword,
        pageNum,
        code: codeArr,
        action,
        area_id,
      } = payload;
      const params = {
        is_district,
        keyword,
        page: pageNum,
        code: codeArr,
        dl: action === 'export' ? '1' : '',
        area_id,
      };
      const response = yield call(getApplyList, params);
      if (!response) return;
      if (action === 'export') {
        __dva_resolve(response);
        return;
      }
      const { code, data, msg } = response;
      const { list, page, total, pageSize } = data;
      let array = list;
      if (code == 0 && list) {
        if (Object.keys(list).length > 0) {
          array = list;
        } else {
          array = [];
          if (!district) {
            message.error('暂无数据');
          }
        }
        if (is_district == 3) {
          yield put({
            type: 'save',
            payload: {
              apply: {
                list: array,
                key,
                keyword,
                paginations: {
                  page: page * 1,
                  count: total * 1,
                  pageSize: pageSize * 1 || 20,
                },
              },
            },
          });
        }
      } else {
        if (is_district == 3) {
          yield put({
            type: 'save',
            payload: {
              apply: {
                list: [],
                key,
              },
            },
          });
        }
        if (!district) {
          message.error(msg);
        }
      }
    },
    *AddAreaPost({ payload, then }, { call, put, select }) {
      const { area, setting, user } = yield select(_ => _);
      const { key } = area || {};
      const {
        currentUser: { user_info = {} },
      } = user || {};
      const { area_ids, inn_area_ids = [] } = user_info;
      const response = yield call(AddAreaPost, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('添加成功');
        yield put({
          type: 'save',
          payload: {
            subordinates: {
              list: [],
            },
          },
        });
        let pianquReqData = {};
        if (setting.options.key == 'yz') {
          // 片区初始值
          pianquReqData =
            inn_area_ids.length > 0
              ? { area_id: area_ids == '*' ? 0 : inn_area_ids.join(',') }
              : {};
        }

        yield put({
          type: 'subList',
          payload: {
            is_district: key == '2' ? 1 : 0,
            keyword: '',
            ...pianquReqData,
          },
        });
        then(code);
      } else {
        message.error(msg);
      }
    },
    *CloseAreaPost({ payload, then }, { call }) {
      const response = yield call(CloseAreaPost, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('申请成功，请耐心等待结果！');
        then(code);
      } else {
        message.error(msg);
      }
    },
    *deleteArea({ payload }, { call, put, select }) {
      const response = yield call(deleteArea, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        const { subordinates } = yield select(_ => _.area);
        const { list } = subordinates;
        for (let i = 0, len = list.length; i < len; i += 1) {
          const payloadId = payload.cm_id;
          if (list[i].cm_id == payloadId) {
            list.splice(i, 1);
            break;
          }
        }
        yield put({
          type: 'save',
          payload: {
            subordinates: {
              list,
            },
          },
        });
        message.success('已删除');
      } else {
        message.error(msg);
      }
    },
    *SendCode({ payload, then }, { call }) {
      const response = yield call(SendCode, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('发送成功！');
      } else {
        message.error(msg);
      }
      then();
    },
    *applyCloseDak({ payload, then }, { call, put, select }) {
      const response = yield call(applyCloseDak, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        const { independent } = yield select(_ => _.area);
        const { list } = independent;
        for (let i = 0, len = list.length; i < len; i += 1) {
          const payloadId = payload.cm_id;
          if (list[i].cm_id == payloadId) {
            list[i].apply_status = '0';
            break;
          }
        }
        yield put({
          type: 'save',
          payload: {
            independent: {
              list,
            },
          },
        });
        message.success('申请成功');
      } else {
        message.error(msg);
      }
      then(code);
    },
    *noPwdLogin({ payload, then }, { call }) {
      const response = yield call(noPwdLogin, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success('登录成功！');
      } else {
        message.error(msg);
      }
      then(code);
    },
    // 待审核驿站审核
    *approved({ payload }, { call, put, select }) {
      const { post, ...rest } = payload;
      const response = yield call(approved, rest);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        // 已决绝驿站，审核通过
        if (post == 6) {
          const { apply = {} } = yield select(_ => _.area);
          const { list } = apply;
          for (let i = 0, len = list.length; i < len; i += 1) {
            const payloadId = payload.cm_id;
            if (list[i].cm_id == payloadId) {
              list[i].passed = true;
            }
          }
          yield put({
            type: 'save',
            payload: {
              apply: {
                list,
              },
            },
          });
          return;
        }
        const { audit } = yield select(_ => _.area);
        const { list } = audit;
        for (let i = 0, len = list.length; i < len; i += 1) {
          const payloadId = payload.cm_id;
          if (list[i].cm_id == payloadId) {
            list[i].passed = true;
          }
        }
        yield put({
          type: 'save',
          payload: {
            audit: {
              list,
            },
          },
        });
        message.success('审核成功！');
      } else {
        message.error(msg);
      }
    },
    // 待审核驿站审核拒绝
    *rejectInn({ payload, __dva_reject, __dva_resolve }, { call, put, select }) {
      const response = yield call(approved, payload);
      if (!response) return;
      const { audit } = yield select(_ => _.area);
      const { list } = audit;
      const { code, msg } = response;
      if (code == 0) {
        message.success('已拒绝');
        for (let i = 0; i < list.length; i += 1) {
          const element = list[i];
          if (element.cm_id == payload.cm_id) {
            element.rejected = true;
          }
        }
        yield put({
          type: 'save',
          payload: {
            audit: {
              list,
            },
          },
        });
        __dva_resolve();
      } else {
        message.error(msg);
        __dva_reject();
      }
    },
    // 中邮，获取下级驿站，已禁用驿站
    *zyGetSubPostStations({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetSubPostStations, payload);
      const { status, keyword, branch_id } = payload;
      if (!response) return;
      const { code, data, msg } = response;
      const { total, page, pageSize, list } = data;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            [status == 2 ? 'forbidden' : 'subordinates']: {
              list,
              // key,
              branch_id,
              keyword,
              paginations: {
                page,
                count: total,
                pageSize,
              },
            },
          },
        });
        __dva_resolve({
          list,
          branch_id,
          keyword,
          paginations: {
            page,
            count: total,
            pageSize,
          },
        });
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 中邮，获取待审核驿站
    *zyGetSubPostStationsToBeChecked({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetSubPostStationsToBeChecked, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const { total, page, pageSize, list } = data;
      const { status, keyword, branch_id } = payload;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            audit: {
              list,
              branch_id,
              keyword,
              status,
              paginations: {
                page,
                count: total,
                pageSize,
              },
            },
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 中邮，获取审核拒绝驿站
    *zyGetSubPostStationsToBeRefus({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetSubPostStationsToBeChecked, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const { total, page, pageSize, list } = data;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            auditrefus: {
              list,
              paginations: {
                page,
                count: total,
                pageSize,
              },
            },
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 中邮，禁用或恢复驿站
    *zyForbidOrRecover({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zyForbidOrRecover, payload);
      if (!response) return;
      const { code, msg } = response;

      if (code == 0) {
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 中邮，审核驿站（通过或拒绝）
    *zyAudit({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zyAudit, payload);
      if (!response) return;
      const { code, msg } = response;

      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 中邮，下属驿站修改支局
    *zyChangeBranch({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(zyChangeBranch, payload);
      if (!response) return;
      const { code, msg } = response;

      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 下属驿站充值
    *charging({ payload, __dva_resolve, __dva_reject }, { call }) {
      const { isZyAccount, ...rest } = payload;
      console.log('isZyAccount', isZyAccount, rest);
      const response = yield call(charging, rest);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        if (isZyAccount == 0) {
          message.success(msg);
        }
        __dva_resolve(response);
      } else {
        message.error(msg);
        __dva_reject(response);
      }
    },
    // 中邮，导出
    *zyExport({ payload, __dva_resolve }, { call }) {
      const response = yield call(zyExport, payload);
      if (!response) return;
      __dva_resolve(response);
    },
    // 下属驿站，获取驿站详情
    *getPostInfo({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getPostInfo, payload);
      if (!response) return;
      const { code, data = {}, msg } = response;
      const {
        cm_id,
        relation,
        source,
        workplace_info,
        business_pattern,
        zone,
        workplace_type,
        mechanism_no,
        create_at,
        inn_name,
        concat_name,
        phone,
        concat_phone,
        province,
        city,
        district,
        town,
        join_at,
        branch = [],
      } = data;
      const baseInfo = {
        inn_name,
        phone,
        cm_id,
        concat_name,
        concat_phone,
        address: `${province}${city}${district}${town}`,
        create_at,
        join_at,
      };

      const businessInfo = {
        relation,
        source,
        workplace_info,
        business_pattern,
        zone,
        workplace_type,
        mechanism_no,
        branch,
      };

      const businessInfoMap = [
        {
          title: '所属支局',
          key: 'branchName',
        },
        {
          title: '经营者与邮政关系',
          key: 'relation',
        },
        {
          title: '驿站来源',
          key: 'source',
        },
        {
          title: '驿站场所信息',
          key: 'workplace_info',
        },
        {
          title: '驿站经营方式',
          key: 'business_pattern',
        },
        {
          title: '掌柜机构号',
          key: 'mechanism_no',
        },
        {
          title: '驿站所属区位',
          key: 'zone',
        },
        {
          title: '驿站所在场所',
          key: 'workplace_type',
        },
      ];

      // 掌柜机构号
      const arr = businessInfoMap.filter(({ key }) => {
        if (!mechanism_no) {
          return key != 'mechanism_no';
        }
        return true;
      });

      if (code == 0) {
        if (branch.length > 0) {
          businessInfo.branchName = branch
            .filter(val => val.level > 0)
            .map(v => v.name)
            .join('');
        }
        businessInfo.path = 'postDetail';

        yield put({
          type: 'save',
          payload: {
            businessInfoMap: arr,
          },
        });

        __dva_resolve(isLegalData({ baseInfo, businessInfo }, {}));
      } else {
        __dva_reject(msg);
        message.error(msg);
      }
    },
    // 下属驿站，修改驿站详情
    *modifyPostInfo({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(modifyPostInfo, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        __dva_resolve(response);
        message.success('修改成功！');
      } else {
        __dva_reject(msg);
        message.error(msg);
      }
    },
    // 下属驿站充值，获取中邮下属驿站列表
    *getZyAccountList({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(getZyAccountList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        const { list = [], total, page, size } = data;
        __dva_resolve({
          list: isLegalData(list),
          paginations: {
            page,
            count: total,
            pageSize: size,
          },
        });
      } else {
        __dva_reject(msg);
        message.error(msg);
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
